/*
 * Copyright (c) 2007-2020 西安交通信息投资营运有限公司 版权所有
 * 作者:赵晨宇
 */

import React, {useCallback} from 'react';
import {Form, Input, Modal, Spin, Switch} from 'antd';
import {SysAppModel} from '../data';
import {EditDialogProps} from "@/global";
import useForm from "@/hooks/useForm";
import useLoad from "@/hooks/useLoad";
import service from "../service";
import useEditModalFooter from "@/hooks/useEditModalFooter";
import useSave from "@/hooks/useSave";
import EditModalFooter from "@/lib/EditModalFooter";
import styles from "@/utils/utils.less";
import {FormInstance} from "antd/lib/form";
import {Store} from "rc-field-form/lib/interface";

const FormItem = Form.Item;

/** 表单布局 */
const formLayout = {
  labelCol: {span: 7},
  wrapperCol: {span: 13},
};

/** 系统应用编辑表单组件 */
const SysAppEdit: React.FC<EditDialogProps> = props => {
  const {params: {created, newModel={status:true}, id, onSubmitSucess}, visible, hide} = props;
  const {form, bind, reset, submit} = useForm();
  const {loading: dataLoading, data: model} = useLoad<SysAppModel>({
    isLoad: Boolean(id),
    isClear: false,
    defaultData: newModel,
    onLoad: () => service.selectById(id),
    onSuccess: bind,
  }, [id]);
  const {finishCallback, ...footerProps} = useEditModalFooter({created,reset,hide,onSubmitSucess});
  const {submitLoading, save} = useSave<SysAppModel>({created, onSave: service.save,});
  const onFinish = useCallback((values: any) => {save(model, values, finishCallback);}, [model]);
  const title = created ? '新建系统应用' : '修改系统应用';

  return (
    <Modal
      title={title}
      visible={visible}
      width={600}
      destroyOnClose
      maskClosable={false}
      onCancel={hide}
      footer={(
        <EditModalFooter
          {...footerProps}
          okLoading={dataLoading || submitLoading}
          onOk={submit}
          onCancel={hide}/>
      )}
    >
      <Spin spinning={dataLoading || submitLoading} wrapperClassName={styles.h100p}>
        {model && (<EditForm {...{form, model, created, onFinish}}/>)}
      </Spin>
    </Modal>
  );
};


/** 表单组件 */
function EditForm(props: { created: boolean, model: SysAppModel, form: FormInstance, onFinish: (values: Store) => void }) {
  const {model, form, onFinish} = props;
  return (
    <Form form={form} onFinish={onFinish} initialValues={model} {...formLayout}>
      <FormItem
        name="name"
        label="应用名称"
        rules={[{required: true, message: '应用名称'}]}
      >
        <Input maxLength={100}/>
      </FormItem>
      <FormItem
        name="status"
        label="状态"
        valuePropName="checked"
      >
        <Switch checked={model.status} />
      </FormItem>
      <FormItem
        name="remark"
        label="备注"
      >
        <Input maxLength={500}/>
      </FormItem>
    </Form>
  );
}

export default SysAppEdit;

